package helpers;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.activiti.engine.task.Task;

import wfm.activiti.ActivitiManager;
import wfm.entities.User;
import wfm.entities.WFInfo;
import wfm.query.QueryDao;

import com.web.util.WebUtils;

@ManagedBean(name = "customerController2")
@SessionScoped
public class CustomerController2 {

	@ManagedProperty(value = "#{user}")
	private User user;
	
	@ManagedProperty(value = "#{wfInfo}")
	private WFInfo wfInfo;

	/** Creates a new instance of LoginControl */
	public CustomerController2() {
	}
	
	/**
	 * Returns the UserGroup of the logged-in User
	 * @return
	 */
	private String getActUserGroup(){
		
		String userGroup=User.GROUP_DESKTOPWORKER;
		
		if(this.user!=null){
			userGroup = this.user.getUserGroup();
		}
		
		return userGroup;
	}

	public String submit2() {
		
		System.out.println("Submit2");
		
		String nextPage = "";

		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();

		try {
			// Submitting task form
			String taskId = this.getTaskId();
			//FIXME: property!!!???
			//manager.getProcessEngine().getFormService().submitTaskFormData(taskId, null);
			manager.getTaskRuntimeService().complete(this.getTaskId());

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		// Check for any execution errors
		String instanceId = this.getInstanceId();
		
		List<Task> tasks = manager.getProcessEngine().getTaskService()
				.createTaskQuery().taskCandidateGroup(getActUserGroup())
				.processInstanceId(instanceId).list();
		
		if (tasks.size() > 0) {
			// Get first task
			Task task = tasks.get(0);
			this.setTaskId(task.getId());

			nextPage = QueryDao.getFormKey(this.getTaskId());
			QueryDao.setAssigneeToTask(task, this.getUser().getName());
			this.setTaskId(task.getId());
		}else{
			FacesContext fc = FacesContext.getCurrentInstance();
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Not accepted role for next step.", null);
		    fc.addMessage(null, msg);
		    fc.renderResponse();
		}

		return WebUtils.redirect(nextPage);
	}

	public WFInfo getWfInfo() {
		return wfInfo;
	}

	public void setWfInfo(WFInfo wfInfo) {
		this.wfInfo = wfInfo;
	}

	public String getInstanceId() {
		return this.wfInfo.getInstanceId();
	}

	public void setInstanceId(String instanceId) {
		this.wfInfo.setInstanceId(instanceId);
	}

	public String getTaskId() {
		return this.wfInfo.getTaskId();
	}

	public void setTaskId(String taskId) {
		this.wfInfo.setTaskId(taskId);
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}
